package com.yxy.chatserver.service.impl;

import com.yxy.chatserver.constant.FriendRequestStatusConstant;
import com.yxy.chatserver.constant.MessageConstant;
import com.yxy.chatserver.domain.po.FriendRequest;
import com.yxy.chatserver.domain.vo.FriendRequestVO;
import com.yxy.chatserver.exception.FriendRequestAlreadyExistsException;
import com.yxy.chatserver.mapper.FriendMapper;
import com.yxy.chatserver.service.FriendRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 朋友请求服务实现类
 */
@Service
public class FriendRequestServiceImpl implements FriendRequestService {

    @Autowired
    private FriendMapper friendMapper;

    /**
     * 创建朋友请求
     *
     * @param fromUserId
     * @param toUserId
     * @param note
     * @param sendTime
     * @return
     */
    @Override
    public FriendRequest createFriendRequest(String fromUserId, String toUserId, String note, LocalDateTime sendTime) {
        // 查询是否已发送过申请
        FriendRequestVO request = friendMapper.findByFromUserIdAndToUserId(fromUserId, toUserId);
        if(request != null){
            throw new FriendRequestAlreadyExistsException(MessageConstant.FRIEND_REQUEST_ALREADY_EXISTS);
        }
        // 添加好友请求
        FriendRequest newFriendRequest = new FriendRequest();
        newFriendRequest.setFromUserId(fromUserId);
        newFriendRequest.setToUserId(toUserId);
        newFriendRequest.setNote(note);
        newFriendRequest.setStatus(FriendRequestStatusConstant.PENDING);
        newFriendRequest.setCreateTime(sendTime);

        friendMapper.addFriendRequest(newFriendRequest);
        return newFriendRequest;
    }

    /**
     * 接受朋友请求
     * @param fromUserId
     * @param toUserId
     * @param status
     * @param sendTime
     */
    @Override
    public void updateFriendRequest(String fromUserId, String toUserId, String status, LocalDateTime sendTime) {
        friendMapper.updateFriendRequestStatus(fromUserId, toUserId, status, sendTime);
    }
}
